<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!-- 取出部署的应用程序名或者是当前的项目名称 -->
<c:set var="ctx" value="${pageContext.request.contextPath}" />

<!DOCTYPE html>
<html lang="zh-CN" class="no-js">
<head>
    <meta charset="UTF-8">
    <title>书籍查看</title>

    <%@include file="/WEB-INF/jsp/common/component/head.jsp"%>
</head>

<body>
    <%@include file="/WEB-INF/jsp/common/component/navbar.jsp"%>

    <div id="left">
        <%@include file="/WEB-INF/jsp/common/component/userMessage.jsp"%>
        <%@include file="/WEB-INF/jsp/common/component/menu.jsp"%>
    </div><!-- /#left -->

    <div id="wrap">
        <div class="content" >
            <div class="inner">
                <ul id="myTab" class="nav nav-tabs">
                    <li class="active"><a href="#table" data-toggle="tab">全部</a></li>
                    <li><a href="#table" data-toggle="tab">已上架</a></li>
                    <li><a href="#table" data-toggle="tab">已下架</a></li>
                </ul>

                <%--<div class="col-sm-3 pull-left">--%>
                    <%--<!-- btn-block 指定按钮和父元素一样大 -->--%>
                    <%--<button type="button" class="btn btn-info ">全部</button>--%>
                    <%--<button type="button" class="btn btn-info col-sm-offset-1">已上架</button>--%>
                    <%--<button type="button" class="btn btn-info col-sm-offset-1">已下架</button>--%>
                <%--</div>--%>
                <input type="hidden" id="userId" value="<%=user.getId()%>">

                <div id="searchPanel" class="panel panel-default" style="margin-top:10px;display: none;">
                    <div class="panel-heading">查询条件</div>
                    <div class="panel-body">
                        <form id="formSearch" class="form-horizontal">
                            <div class="form-group" style="margin-top:15px">
                                <label class="control-label col-sm-1" for="txt_search_departmentname">部门名称</label>
                                <div class="col-sm-3">
                                    <input type="text" class="form-control" id="txt_search_departmentname">
                                </div>
                                <label class="control-label col-sm-1" for="txt_search_statu">状态</label>
                                <div class="col-sm-3">
                                    <input type="text" class="form-control" id="txt_search_statu">
                                </div>
                                <div class="col-sm-4" style="text-align:left;">
                                    <button type="button" style="margin-left:50px" id="btn_query" class="btn btn-primary">查询</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div id="toolbar" class="btn-group">
                    <a id="addBtn" href="${ctx}/book/create" class="btn btn-default">
                        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
                    </a>
                    <%--<button id="btn_edit" type="button" class="btn btn-default">--%>
                        <%--<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改--%>
                    <%--</button>--%>
                    <button id="delBtn" type="button" class="hidden btn btn-default">
                        <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
                    </button>
                    <button id="searchBtn" type="button" class="hidden btn btn-default">
                        <span class="glyphicon glyphicon-search" aria-hidden="true"></span>查询
                    </button>
                </div>

                <table id="table">
                </table>
            </div>
        </div><!-- /#content -->
        <%@include file="/WEB-INF/jsp/common/component/footer.jsp"%>
    </div><!-- /#wrap -->
    <%@include file="/WEB-INF/jsp/common/component/foot.jsp"%>

    <script>
        function toggleStatus(bookId, currentStatus){
            var ac = currentStatus == book_status_up ? "下架" : "上架";
            swAjax({
                title: ac + "书籍",
                text: "您确定要" + ac + "该书籍吗?",
                callback: function(){
//                    waitMessage();
                    $.ajax({
                        url: path + "/book/toggleStatus",
                        type: "post",
                        dataType: "json",
                        data:{
                            bookId: bookId,
                            userId: $("#userId").val(),
                            currentStatus: currentStatus
                        },
                        success: function(data){
                            if(data.success){
                                successMessage("操作成功", function(){
                                    table.bootstrapTable('refresh');
                                });
                            } else{
                                errorMessage("操作失败！请重试");
                            }
                        }
                    });
                }
            });
        }

        function deleteFun(bookId){
            swAjax({
                title: "删除书籍",
                text: "您确定要删除该书籍吗?",
                callback: function(){
//                    waitMessage();
                    $.ajax({
                        url: path + "/book/deleteByUser",
                        type: "post",
                        dataType: "json",
                        data:{
                            bookId: bookId,
                            userId: $("#userId").val()
                        },
                        success: function(data){
                            if(data.success){
                                successMessage("操作成功", function(){
                                    table.bootstrapTable('refresh');
                                });
                            } else{
                                errorMessage("操作失败！请重试");
                            }
                        }
                    });
                }
            });
        }

        function statusFormatter(value, row, index){
            return book_status[value];
        }

        function actionFormatter(value, row, index){
            var res;
            var ac;
            res = "<a href='" + path + "/book/detail?id="+ row.id + "' class='btn btn-info btn-sm'>查看</a> &nbsp;&nbsp;";

            res += "<a href='" + path + "/book/update?id="+ row.id + "' class='btn btn-info btn-sm'>修改</a> &nbsp;&nbsp;";

            if(row.status == book_status_up){
                ac = "下架";
            } else{
                ac = "上架";
            }
            res += "<button onclick='toggleStatus(\"" + row.id + "\", " + row.status + ")' type='button' class='btn btn-info btn-sm'>" + ac + "</button> &nbsp;&nbsp;";

            res += "<button onclick='deleteFun(\"" + row.id + "\")' type='button' class='btn btn-danger btn-sm'>删除" + "</button> &nbsp;&nbsp;";

            return res;
        }

        var table = $('#table');

        $(document).ready(function(){
            //查询的 JSON 对象，发送时转成字符串
            var filter = {
                "owner.id":{
                    type: "string",
                    filter: {
                        eq: '${user.id}'
                    }
                }
            };

            $("#searchBtn").click(function(){
               $("#searchPanel").fadeToggle(800);
            });

            table.bootstrapTable({
                //定义列
                columns: [
                    {field: 'checkbox', title:'', checkbox: true},
                    {field: 'id', title: '', visible: false},
//                    {field: 'cover', title: '封面', titleTooltip: "封面"},
                    {field: 'name', title: '书名', titleTooltip: "书名"},
                    {field: 'publishingHouse', title: '出版社',titleTooltip: "出版社"},
                    {field: 'publicationYear', title: '出版年份',titleTooltip: "出版年份"},
                    {field: 'price', title: '价格',titleTooltip: "价格"},
                    {field: 'status', title: '状态',titleTooltip: "状态", formatter: statusFormatter},
                    {field: 'action', title: '操作',titleTooltip: "操作", formatter: actionFormatter}
                ],
                url: '${ctx}/book/pageData',    //A URL to request data from remote site.
                method: 'get',           //	The method type to request remote data.
                contentType: 'application/json',  //The contentType of request remote data.
                dataType: 'json',            //希望服务器返回的数据类型
                sidePagination: 'server',   //设置为服务器分页
                toolbar: '#toolbar',        //工具按钮用哪个容器
                queryParams: function(params){
                    return {
                        page: params.pageNumber,
                        pageSize: params.pageSize,
                        filter: hasData(filter) ? JSON.stringify(filter) : null,
                        sortName: params.sortName,
                        sortOrder: params.sortOrder
                    };
                },

                queryParamsType: '',   //Set 'limit' to send query params width RESTFul type.

                responseHandler: function(data) {
                    var res = data.dataObj;
                    console.info("res:" + res);
                    var tmp;
                    for(var i=0; i<res.length; ++i){
                        tmp = res[i];

                        //封面
                        res[i].cover = str2img(res[i].cover);
                        console.info("cover:" + res[i].cover);

//                        res[i].action = makeBtn();
                    }
                    return {
                        "rows": res,
                        "total": data.total
                    };
                },
                striped: true,           //表格加上条纹，默认为 false
                pagination: true,       //是否展示页脚，默认为 false
                selectItemName: "btn",  //The name of radio or checkbox input.
//                search: true,           //搜索框，默认为 false
                showRefresh: true,        //刷新按钮
//                showColumns: true,        //可以让用户选择要显示的列
                showToggle: true,            //切换表格风格：列表/卡片
                idField: 'id',               //指明那一列是主键
                clickToSelect: true,
                valign: "middle",
//        cardView: true,              //是否以卡片形式展示，默认为 false
                paginationDetailHAlign: 'right',    //页码字显示的位置,left/right
                checkboxHeader: false,            //设为 false，则没有选中全部的 checkbox 按钮
                singleSelect: true             //设置 checkbox 仅能选中一行
            });

            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                // 获取已激活的标签页的名称
                var activeTab = $(e.target).text();
                switch(activeTab){
                    case "全部":
                        console.info("quanbu!");
                        filter = {
                            "owner.id":{
                                type: "string",
                                filter: {
                                    eq: '${user.id}'
                                }
                            }
                        };break;
                    case "已上架":
                        filter = {
                            "owner.id":{
                                type: "string",
                                filter: {
                                    eq: '${user.id}'
                                }
                            },
                            status:{
                                type: "int",
                                filter: {
                                    eq: book_status_up
                                }
                            }
                        }; break;
                    case "已下架":filter = {
                        status:{
                            "owner.id":{
                                type: "string",
                                filter: {
                                    eq: '${user.id}'
                                }
                            },
                            type: "int",
                            filter: {
                                eq: book_status_down
                            }
                        }
                    }; break;
                }
                table.bootstrapTable('refresh');
            });
        });
    </script>
</body>

</html>